/**
 * 通讯接口
 */

// 端沟通接口
window.jsToNative = {
  type: "",
  nativeCallbacks: {},
  actionPrefix: "",
  nativeInvokeHandler: null,
  isNative: true,
  nativeToH5: function(param, callBack, mode) {
    if (callBack) {
      this.nativeCallbacks[param.action] = {
        func: callBack,
        mode: mode || "once"
      };
    }
    this.getNativeStringify(param);
  },
  nativeInvoke: function(param, callBack, mode) {
    if (callBack) {
      const callBackId =
          "cb" + new Date().getTime() + Math.round(Math.random() * 1000) + "Func";
      this.nativeCallbacks[callBackId] = {
        func: callBack,
        mode: mode || "once"
      };
      param.callBackScript =
          "window.jsToNative.nativeCallbacks." + callBackId + ".func";
      // once代表函数只调用一次，默认可反复调用
      param.mode = mode || "once";
    }
    this.getNativeStringify(param);
  },

  // 转换参数 -> json.stringify
  getNativeStringify: function(param) {
    try {
      param.action = this.actionPrefix + param.action;
      const paramString = JSON.stringify(param);
      if (this.isNative) {
        if (this.getType() == "android") {
          window.nativeObject.jsToNative(paramString);
        } else if (this.getType() == "ios") {
          window.webkit.messageHandlers.jsToNative.postMessage(paramString);
        }
      } else {
        this.nativeInvokeHandler(paramString, "*"); // 解决iframe跨域访问权限
      }
    } catch (e) {
      //
    }
  },

  // 需要通信的原生类型
  getType: function() {
    if (this.type) {
      return this.type;
    }
    const u = navigator.userAgent;
    const isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1;
    const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    if (isAndroid) {
      this.type = "android";
    } else if (isiOS) {
      this.type = "ios";
    }
    return this.type;
  }
};

/**
 * 与客户端通讯接口
 * @type {Object}
 */

window.clientInterface = {
  /**
   * [ getNativeGoBack 页面返回    ->   会议会展]
   * @param  {[Function]} nativeInvoke [ H5 调用 Native 通用 ]
   * @param  {[Function]} callBack  [ 回调方法 ]
   */
  getNativeGoBack: function(callBack) {
    const requestParams = {
      action: "getNativeGoBack"
    };
    window.jsToNative.nativeInvoke(requestParams, callBack);
  }
};
